package cn.jofei.core;

import cn.jofei.common.ano.Resource;
import cn.jofei.common.ano.Value;
import cn.jofei.common.config.AppProperties;
import cn.jofei.common.util.Utils;
import cn.jofei.core.bean.BeanFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.Locale;
import java.util.Optional;

/**
 * Invoker
 *
 * @author Jofei Bao
 * @version ngbao v1.0.2
 * @date 2022/7/11 17:20
 */
public class Invoker {

    public static final Logger log = LoggerFactory.getLogger(Invoker.class);

    public static String initInstance(Object instance) {
        Class<?> aClass = instance.getClass();
        try {
            for (Field field : aClass.getDeclaredFields()) {
                Resource resource = field.getDeclaredAnnotation(Resource.class);
                Value value = field.getDeclaredAnnotation(Value.class);
                field.setAccessible(true);

                Class<?> type = field.getType();
                Object fieldValue = field.get(instance);
                if (resource != null) {
                    //注入的bean名称
                    String beanName = Utils.isNull(resource.name()) ? beanName(type) : resource.name();
                    Object bean = BeanFactory.getBean(beanName);
                    // TODO: 2022/10/27 循环依赖问题？
                    initInstance(bean);
                    if (Utils.nonNull(bean)) {
                        field.set(instance, bean);
                    } else {
                        return beanName(aClass);
                    }
                } else if (value != null) {
                    String name = value.name();
                    if (Utils.nonNull(name)) {
                        if (name.contains("${")) {
                            name = name.substring("${".length(), name.indexOf("}"));
                        }
                        Optional<?> o = AppProperties.get(name, type);
                        if (o.isPresent()) {
                            field.set(instance, o.get());
                        } else {
                            if (fieldValue == null) {
                                throw new RuntimeException("请配置默认属性：" + name);
                            }
                        }
                    } else {
                        throw new RuntimeException("注解：" + Value.class + "不能为空");
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    public static String beanName(Class<?> type) {
        if (type != null) {
            String name = type.getName();
            String bean = name.substring(name.lastIndexOf(".") + 1);
            String first = String.valueOf(bean.charAt(0));
            return bean.replaceFirst(first, first.toLowerCase(Locale.ROOT));
        }
        return "";
    }
}
